<template>
	<div class="admin_shopping">
		<table style="border:1px solid ; width: 80%;height: 600px;">
			<tr>
				<td>
					<input type="checkbox" v-model="checkAll" @change="check()" />
				</td>
				<td>商品</td>
				<td>书名</td>
				<td>价格</td>
				<td>数量</td>
			</tr>
			<tr v-for="(item , i) in goods">
				<td>
					<input type="checkbox" :value="i" v-model="arr" name="checkOtherther" @change="checkOther()" />
				</td>
				<td><img :src="`http://127.0.0.1/api/public/showimg/${item.book.pic}`"
						style="width: 70%;height: 80%;" /></td>
				<td>{{item.book.name}}</td>
				<td>{{item.price}}</td>
				<td style="display: flex;margin-top: 50px;">
					<button style="width: 40px; height: 25px;" @click="ToggleNum(i , -1)">-</button>
					{{item.num}}
					<button style="width: 40px; height: 25px;" @click="ToggleNum(i , 1)">+</button>
				</td>
				<td>
					<a href="#" @click="del(i)">删除</a>
				</td>
			</tr>
		</table>
		<p>
			计算总价:￥{{sumprice}}
		</p>
	</div>
</template>

<script>
	export default {
		name: 'MobileShopping',
		data() {
			return {
				activ:"color: #fffffb8",
				goods: [],
				sumprice: 0,
				arr: [],
				checkAll: false,
			}
		},
		methods: {
			head(){
				this.activ="color: #ffffff"
			},
			foot(){
				this.activ="color : #fffffb8"
			},
			handleChange(value) {
				console.log(value);
			},
			ToggleNum(i, num) {
				this.goods[i].num += num;
				if (this.goods[i].num < 1) {
					this.goods[i].num = 1;
				} else if (this.goods[i].num > 10) {
					this.goods[i].num = 10;
				};
				this.arr.push(i);
				this.arr = Array.from(new Set(this.arr));
				this.SumPrice();
			},
			del(i) {
				//找到这个数据在arr中的下标
				let j = this.arr.indexOf(i);
				this.arr.splice(j, 1);

				this.sumprice = 0;
				for (let item of this.arr) {
					console.log(item);
					let sum = this.goods[item].num * this.goods[item].price;
					this.sumprice += sum;
				};
				this.arr.forEach((item, k) => {
					console.log(item);
					if (item > i) {
						this.arr[k]--;
					}
				});
				this.goods.splice(i, 1);
			},
			SumPrice() {
				this.sumprice = 0;
				for (let i of this.arr) {
					let sum = this.goods[i].num * this.goods[i].price;
					this.sumprice += sum;
				}
			},
			checkOther() {
				this.checkAll = this.arr.length == this.goods.length ? true : false;
				this.SumPrice();
			},
			check() {
				if (this.checkAll) {
					for (let i in this.goods) {
						this.arr.push(Number(i));
					}
				} else {
					this.arr = [];
				};
				this.arr = Array.from(new Set(this.arr));
				this.SumPrice();
			},
		},
		mounted() {
			let token = window.localStorage.getItem("token");
			this.$get("/api/fore/cart/findMyCarts").then((resp) => {
				this.goods = resp.data.data
				console.log(this.goods);
			})
		}
	}
</script>

<style scoped>
	.admin_shopping {
		width: 100%;
	}

	.admin_shopping table {}
	.admin_shopping table td{
		width: 30%;
		height: 90px;
	}
	.admin_shopping td img {}
</style>